layui.define(['jquery'], function (exports) {
    var $ = layui.jquery;

    var userPermission = {
        checkLogin: function () {
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/check_login',
                type: 'GET',
                dataType: 'JSON',
                success: function (data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.msg('未登录。');
                        window.location.href = '/page/login.html'
                    }
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.msg('未知错误。');
                }
            });
        },
        login: function (un, pw) {
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/login',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    un: un,
                    pw: pw
                },
                success: function (data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.msg(data.msg);
                    } else {
                        window.location.href = '/';
                    }
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.msg('未知错误。');
                }
            });
        },
        logout: function () {
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/logout',
                type: 'GET',
                dataType: 'JSON',
                success: function (data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.msg(data.msg);
                    } else {
                        window.location.href = '/page/login.html';
                    }
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.msg('未知错误。');
                }
            });
        }
    };
    
    exports('userPermission', userPermission);
});
